package com.fengmi.pay.controller;

import com.fengmi.pay.config.WXConfig;
import com.fengmi.pay.service.IPayService;
import com.fengmi.vo.ResultVO;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("wx")
public class WxPayController {

    @Autowired
    private IPayService payService;



    @RequestMapping("pay/{ordersn}")
    public ResultVO pay(@PathVariable String ordersn){

        return payService.pay(ordersn);
    }



    //微信回调接口，给微信调用的，微信异步通知支付结果

    //
    @RequestMapping("notify")
    public String notify(HttpServletRequest request){
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = inStream.read(buffer)) != -1){
                outSteam.write(buffer,0,len);
            }
            outSteam.close();
            inStream.close();
            String resultXML = new String(outSteam.toByteArray(),"utf-8");
            System.out.println(resultXML);
            ResultVO resultVO = payService.notify(resultXML);


            if(resultVO.isSuccess()){
                //给微信规范响应
                Map responseMap = new HashMap();
                responseMap.put("return_code", "SUCCESS");
                responseMap.put("return_msg", "OK");

                return WXPayUtil.generateSignedXml(responseMap, new WXConfig().getKey());
            }

            Map responseMap = new HashMap();
            responseMap.put("return_code", "FAIL");
            responseMap.put("return_msg", "bu OK");
            return WXPayUtil.generateSignedXml(responseMap, new WXConfig().getKey());



        } catch (Exception e) {
            e.printStackTrace();
            Map responseMap = new HashMap();
            responseMap.put("return_code", "FAIL");
            responseMap.put("return_msg", "bu OK");

            try {
                return WXPayUtil.generateSignedXml(responseMap, new WXConfig().getKey());
            } catch (Exception exception) {
                exception.printStackTrace();
                return  "";
            }
        }
    }

}
